package fun.sssdnsy.controller;

import javafx.scene.Node;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.*;
import org.fxmisc.richtext.LineNumberFactory;
import org.fxmisc.richtext.StyleClassedTextArea;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;

public class RichTextEditor extends StyleClassedTextArea {

    private static final transient Logger log = LoggerFactory.getLogger(RichTextEditor.class);


    public RichTextEditor() {
        configureEditor();
        setupShortcuts();
    }

    private void configureEditor() {

        this.setParagraphGraphicFactory(LineNumberFactory.get(this));

        this.setWrapText(true);
        this.setMouseOverTextDelay(java.time.Duration.ofMillis(500));

        // 图片拖放支持
        this.setOnDragOver(event -> {
            if (event.getDragboard().hasFiles()) {
                event.acceptTransferModes(TransferMode.COPY);
            }
            event.consume();
        });

        this.setOnDragDropped(event -> {
            event.getDragboard().getFiles().forEach(this::insertImage);
            event.setDropCompleted(true);
            event.consume();
        });
    }

    private void setupShortcuts() {
        this.addEventFilter(KeyEvent.KEY_PRESSED, this::handleGlobalKeyEvents);
    }

    private void handleGlobalKeyEvents(KeyEvent event) {
        // 创建跨平台快捷键组合（Windows/Linux用Ctrl，Mac用Command）
        KeyCombination saveShortcut = new KeyCodeCombination(
                KeyCode.S,
                KeyCombination.SHORTCUT_DOWN
        );
        KeyCombination boldShortcut = new KeyCodeCombination(
                KeyCode.B,
                KeyCombination.SHORTCUT_DOWN
        );

        KeyCombination deletelineShortcut = new KeyCodeCombination(
                KeyCode.D,
                KeyCombination.SHORTCUT_DOWN
        );

        KeyCombination imagePasteShortcut = new KeyCodeCombination(
                KeyCode.V,
                KeyCombination.SHORTCUT_DOWN
        );


        if (saveShortcut.match(event)) {
            log.info("Ctrl+S/Command+S 触发保存");

            // 阻止事件继续传播
            event.consume();
        }

        if (boldShortcut.match(event)) {
            log.info("Ctrl+S/Command+S 触发加粗");
            applyBoldStyle();

            event.consume();
        }

        if (deletelineShortcut.match(event)) {
            log.info("Ctrl+S/Command+D 触发当前行");
            deleteCurrentLine();
            event.consume();
        }

        if (imagePasteShortcut.match(event)) {
            Clipboard clipboard = Clipboard.getSystemClipboard();
            if (clipboard.hasImage()) {
                log.info("Ctrl+S/Command+V 触发插入图片");
                handleImagePaste();
                event.consume();
            }

        }
    }

    public void insertImage(int position, Image image) {
        ImageView imageView = createImageView(image);
        this.insert(position, "", (Collection<String>) imageView);
    }

    private ImageView createImageView(Image image) {
        ImageView imageView = new ImageView(image);
        imageView.setPreserveRatio(true);
        imageView.setFitWidth(200);
        return imageView;
    }

    private void insertImage(File imageFile) {
        try {
            Image image = new Image(new FileInputStream(imageFile));
        } catch (IOException e) {
            log.error("图片加载失败: " + e.getMessage());
        }
    }

    private void applyBoldStyle() {
        this.setStyle(
                this.getSelection().getStart(),
                this.getSelection().getEnd(),
                Collections.singleton("-fx-font-weight: bold;")
        );
    }


    private void handleImagePaste() {
        Clipboard clipboard = Clipboard.getSystemClipboard();
        if (clipboard.hasImage()) {
            insertImage(this.getCaretPosition(), clipboard.getImage());
        }
    }

    private void deleteCurrentLine() {
        int paragraph = getCurrentParagraph();

    }

    private void duplicateLine() {
        int paragraph = getCurrentParagraph();
        String text = getText(paragraph);
        //  insertText(offset(paragraph, getParagraphLength(paragraph)), "\n" + text);
    }

    public interface SaveHandler {
        void handleSave();
    }

    private SaveHandler saveHandler;

    public void setSaveHandler(SaveHandler handler) {
        this.saveHandler = handler;
    }

    public Node getNode(int position) {
        return null;//getContent().getNode(position); // 正确获取节点
    }

    public int getParagraphEnd(int paragraph) {
        return 0;// offset(paragraph, getParagraphLength(paragraph));
    }

    public void appendText(String text) {
        insertText(getLength(), text);
    }

    public void setText(String text) {
        replaceText(0, getLength(), text);
    }
    // endregion
}
